// 文件自动导入
const requireDirectory = require('require-directory')
const Router = require('koa-router')

class InitManager {
  static initCore(app) {
    // 入口方法
    InitManager.app = app
    InitManager.initLoadRouters()
    InitManager.loadConfig()
    InitManager.loadError()
    
  }
  static initLoadRouters() {
    const apiDirectory = `${process.cwd()}/app/api`
    requireDirectory(module, apiDirectory, {visit: whenLoadModule})

    function whenLoadModule(obj) {
      if(obj instanceof Router) {
        InitManager.app.use(obj.routes())
      }else {
        if(obj instanceof Object && obj.router) {
          for(let r in obj) {
            InitManager.app.use(obj[r].routes())
          }
        }
      }
    }
  }
  // 加载全局变量
  static loadConfig(path = '') {
    const configPath = path || process.cwd() + '/config/config.js'
    const config = require(configPath)
    global.config = config
  }

  // 加载全局异常提示
  static loadError() {
    const errors = require('./http-exception')
    global.errs = errors
  }
}

module.exports = InitManager